package kyssion.leetcode.num101_150;

public class code150_逆波兰表达式求值 {
    public static void main(String[] args) {
        System.out.println(new code150_逆波兰表达式求值().evalRPN(
                new String[]{
                        "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"
                }
        ));
    }

    public int evalRPN(String[] tokens) {
        int index = 0;
        for (int a = 0; a < tokens.length; a++) {
            if ("+".equals(tokens[a])) {
                if (index >= 2) {
                    int one = Integer.parseInt(tokens[--index]);
                    int two = Integer.parseInt(tokens[--index]);
                    tokens[index++] = String.valueOf(one + two);
                }
            } else if ("-".equals(tokens[a])) {
                if (index >= 2) {
                    int one = Integer.parseInt(tokens[--index]);
                    int two = Integer.parseInt(tokens[--index]);
                    tokens[index++] = String.valueOf(two - one);
                }
            } else if ("*".equals(tokens[a])) {
                if (index >= 2) {
                    int one = Integer.parseInt(tokens[--index]);
                    int two = Integer.parseInt(tokens[--index]);
                    tokens[index++] = String.valueOf(one * two);
                }
            } else if ("/".equals(tokens[a])) {
                if (index >= 2) {
                    int one = Integer.parseInt(tokens[--index]);
                    int two = Integer.parseInt(tokens[--index]);
                    tokens[index++] = String.valueOf(two / one);
                }
            } else {
                tokens[index++] = tokens[a];
            }
        }
        return Integer.parseInt(tokens[0]);
    }
}